package com.code.generator.cn.util.base;

import com.alibaba.fastjson.JSON;
import com.code.generator.cn.entity.CoderField;
import com.code.generator.cn.entity.CoderTable;
import com.code.generator.cn.util.MyFileUtil;
import com.code.generator.cn.util.PathUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class EntityUtil {

    /**
     * 生成对应的entity
     * @param coderTable
     * @param coderFields
     * @param configuration
     * @param uploadPath
     */
    public static void createEntity(CoderTable coderTable, List<CoderField> coderFields, Configuration configuration, String uploadPath) throws IOException, TemplateException {
        Template temp=configuration.getTemplate("/code/entity.ftl");
        Writer file =null;
           String packageName=coderTable.getPackageName();
           /* //获取包名
            String packageName=coderTable.getPackageName();
            String groupPath=packageName.replace(".","/");
            //生成entity的路径
            String entityPath="";
            if(StringUtils.isEmpty(coderTable.getModalName())){
                entityPath= uploadPath+"/src/main/java/"+groupPath+"/entity/";
            }else{
                entityPath= uploadPath+"/src/main/java/"+groupPath+"/"+coderTable.getModalName()+"/entity/";
            }*/
            String entityPath=PathUtil.createFileBasePath(coderTable,uploadPath)+"/entity/";

            //设置生成的路径
            MyFileUtil.createFileDir(entityPath);
            //设置生成的属性
            Map<String,Object> createMap=new HashMap<>();
            //设置实体对象要生成的包名
            createMap.put("packageName",PathUtil.createPackageName(coderTable));
            //设置实体对象的类名
            String className=coderTable.getModifyName();
            createMap.put("className",className);

            //设置字段属性
            List<Map<String,Object>> fieldList=new ArrayList<>();
            for (CoderField coderField : coderFields) {
                Map<String, Object> fieldMap = CommonUtil.createFieldMap(coderField,createMap);
                fieldList.add(fieldMap);
            }
            if(!createMap.containsKey("DATEIMPORT")){
                createMap.put("DATEIMPORT","");
            }
            createMap.put("fieldList",fieldList);



            //设置生成的文件名
            file = new FileWriter(entityPath+className+".java");
            temp.process(createMap, file);
            log.info(JSON.toJSONString(createMap));
            file.close();

    }
}
